package taller2.controller.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;

import taller2.view.components.LoadBar;
import taller2.view.menus.CodeBrowser;

public class LoadCodeMenuListener implements ActionListener{
	private LoadBar bar;
	private CodeBrowser browser;
	private JFileChooser chooser;
	
	// constructor
	public LoadCodeMenuListener(LoadBar bar,CodeBrowser browser){
		this.bar = bar;
		this.browser = browser;
		chooser = new JFileChooser();
	}
	
	// detects and executes the events
	public void actionPerformed(ActionEvent event){
		Object source = event.getSource(); 	
		
		if(bar.isSelectButton(source)){
			chooser.showOpenDialog(null);
			File selectedFile = chooser.getSelectedFile();
			if(selectedFile != null){
				String path = selectedFile.getAbsolutePath();
				bar.setPath(path);					
			}
		}else if (bar.isLoadButton(source)){
			String path = bar.getPath();
			if(new File(path).exists()){
				browser.changeCode(path);
			}
		}
		bar.unselectButtons();		
	}
}
